Ext.define('Seq.tree.Filter', {
    extend: "Ext.form.field.Text",
    xtype: "xtreefilter",
    maxLength: 20,
    emptyText: '按名称过滤',

    triggers: {
        clear: {
            cls: 'x-form-clear-trigger',
            handler: function (cmp, trigger) {
                cmp.setValue('');
                cmp.search();
                trigger.hide();
            },
            hidden: true,
            scope: this
        },
        search: {
            cls: 'x-form-search-trigger x-fa fa-action',
            weight: 1,
            handler: function (cmp, trigger) {
                cmp.search();
                cmp.getTrigger('clear').show();
            },
            scope: this
        }
    },

    initComponent: function () {
        var me = this;
        me.callParent(arguments);
        me.on('specialkey', function (cmp, e) {
            if (e.getKey() == e.ENTER)
                cmp.getTrigger('search').handler(cmp);
        });
    },

    getTree: function () {
        return this.up('treepanel');
    },

    clear: function () {
        var me = this, tree = me.getTree(), store = tree.store;
        store.removeFilter('stringfilter');
        // grid.getView().refresh();
    },

    storeFilter: function (store, value) {
        var visibles = [];
        store.getRoot().cascadeBy(function (item) {
            if (-1 < item.data.text.indexOf(value)) {
                Ext.Array.push(visibles, item.data.uid);
                while (item.parentNode) {
                    item = item.parentNode;
                    if (!Ext.Array.contains(visibles, item.data.uid)) {
                        Ext.Array.push(visibles, item.data.uid);
                    }
                }
            }
        });
        var stringFilter = new Ext.util.Filter({
            id: 'stringfilter',
            visibles: visibles,
            filterFn: function (item) {
                if (Ext.Array.contains(this.visibles, item.data.uid)) {
                    if (item.childNodes.length > 0) {
                        item.data.expanded = true;
                    }
                    return true;
                }
                return false;
            }
        });
        store.addFilter(stringFilter);
    },

    search: function () {
        var me = this, tree = me.getTree(), store = tree.getStore(), text = me.getValue();
        if (0 == text.length) {
            me.clear();
            return;
        }
        me.storeFilter(store, text);
    }

});